<?php

namespace App\Interceptor;

use App\Util\AuthUtil;
use App\Util\Result;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;

class RouteInterceptor implements EventSubscriberInterface
{

    private AuthUtil $authUtil;

    public function __construct(AuthUtil $authUtil)
    {
        $this->authUtil = $authUtil;
    }

    public static function getSubscribedEvents(): array
    {
        return [
            KernelEvents::REQUEST => ['onKernelRequest', 9999],
        ];
    }

    public function onKernelRequest(RequestEvent $event)
    {
        $route = array('/chapters'); // 要拦截的路由
        $request = $event->getRequest();

        $result = new Result();
        $response = new JsonResponse();
        $response->setStatusCode(403);

        // 所有的请求头
        $headers = $request->headers->all();

        // 否则获取请求头 解码token再校验

        foreach ($route as $r) {
            if ($request->getPathInfo() === $r) {
                // 不存在请求头
                if (!in_array("authorization", array_keys($headers))) {
                    $response->setData($result->noPermission("Missing request header"));
                    $event->setResponse($response);
                    return;
                }

                $token = $headers['authorization'][0] ?? 1;
                if (empty($token)) {// 存在请求头 单位空
                    $response->setData($result->noPermission("Not logged in."));
                    $event->setResponse($response);
                } else { // 请求头内容不为空
                    if (!$this->authUtil->decodeToken($token)) {
                        $response->setData($result->noPermission("Invalid token."));
                        $event->setResponse($response);
                    }else{
                        $sessionToken = $request->getSession()->get("token");
                        if ($sessionToken==null ||$sessionToken != $token){
                            $response->setData($result->noPermission("Invalid token."));
                            $event->setResponse($response);
                        }
                    }
                }
            }
        }
    }
}